package com.javasm.finance.filter;

import com.javasm.finance.entity.CodeAndMsg;
import com.javasm.finance.entity.ReturnEntity;
import com.javasm.finance.util.RespUtils;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

@WebFilter("/*")
public class CFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req=(HttpServletRequest)servletRequest;
        HttpServletResponse resp=(HttpServletResponse)servletResponse;
        String servletPath = req.getServletPath();
        HttpSession session = req.getSession();
        List<String> loginUserMenuUrl = (List<String>) session.getAttribute("loginUserMenuUrl");
        if ("/login".equals(servletPath)||"/main".equals(servletPath)||"/logout".equals(servletPath)){//||"/prod1".equals(servletPath)
            filterChain.doFilter(servletRequest,servletResponse);
        }else {
            if (loginUserMenuUrl.contains(servletPath)) {
                filterChain.doFilter(servletRequest,servletResponse);
            }else {
                ReturnEntity re = new ReturnEntity();
                re.setReturnCode(CodeAndMsg.NO_AUTH.getReturnCode());
                re.setReturnMsg(CodeAndMsg.NO_AUTH.getReturnMsg());
                RespUtils.handleResp(resp,re);
            }
        }
    }

    @Override
    public void destroy() {

    }
}
